package com.lmx.common.util;

import java.util.Random;
import java.util.TreeMap;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.misc.BASE64Encoder;

import com.lmx.common.constants.CommonConstants;
import com.qcloud.QcloudApiModuleCenter;
import com.qcloud.Module.Vod;
import com.qcloud.Utilities.Json.JSONObject;

/**
 * 腾讯云相关交互
 *
 * @author ytche
 * @date 2017年8月17日
 *
 */
public class QCloudUtil {
	private static Log logger = LogFactory.getLog(QCloudUtil.class);
	private static final String HMAC_ALGORITHM = "HmacSHA1";
	private static final String CONTENT_CHARSET = "UTF-8";
	private static final Integer SUCCESS_CODE = 0;

	public static byte[] byteMerger(byte[] byte_1, byte[] byte_2) {
		byte[] byte_3 = new byte[byte_1.length + byte_2.length];
		System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
		System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
		return byte_3;
	}

	/**
	 * 生成签名
	 *
	 * @author ytche
	 * @param currentTime
	 *            当前时间戳(秒)
	 * @param validTime
	 *            有效时间(秒)
	 * @param random
	 *            随机数
	 * @return
	 * @date 2017年8月17日 下午5:06:50
	 */
	@SuppressWarnings("restriction")
	public static String GetUploadSignature(long currentTime, long validTime,
			int random) {
		String strSign = "";
		String contextStr = "";
		long endTime = (currentTime + validTime);
		try {
			contextStr += "secretId="
					+ java.net.URLEncoder.encode(
							CommonConstants.TECENT_CLOUD_SECRETID, "utf8");
			contextStr += "&currentTimeStamp=" + currentTime;
			contextStr += "&expireTime=" + endTime;
			contextStr += "&random=" + random;

			Mac mac = Mac.getInstance(HMAC_ALGORITHM);
			SecretKeySpec secretKey = new SecretKeySpec(
					CommonConstants.TECENT_CLOUD_SECRETKEY
							.getBytes(CONTENT_CHARSET),
					mac.getAlgorithm());
			mac.init(secretKey);
			byte[] hash = mac.doFinal(contextStr.getBytes(CONTENT_CHARSET));
			byte[] sigBuf = byteMerger(hash, contextStr.getBytes("utf8"));
			strSign = new String(new BASE64Encoder().encode(sigBuf).getBytes());
			strSign = strSign.replace(" ", "").replace("\n", "")
					.replace("\r", "");
		} catch (Exception e) {
			logger.error(e);
			return "";
		}
		return strSign;
	}

	/**
	 * 获取上传签名
	 *
	 * @author ytche
	 * @return
	 * @date 2017年8月17日 下午5:16:33
	 */
	public static String GetUploadSignature() {
		long currentTime = System.currentTimeMillis() / 1000;
		long validTime = 3600 * 3;
		int random = new Random().nextInt(Integer.MAX_VALUE);
		return QCloudUtil.GetUploadSignature(currentTime, validTime, random);
	}

	/**
	 * 删除云端视频
	 *
	 * @author ytche
	 * @param fileId
	 * @return
	 * @date 2017年8月21日 下午2:16:58
	 */
	public static boolean deleteVideo(String fileId) {
		boolean rtn = false;
		TreeMap<String, Object> config = QCloudUtil.getConfig();
		QcloudApiModuleCenter module = new QcloudApiModuleCenter(new Vod(),
				config);

		TreeMap<String, Object> params = new TreeMap<String, Object>();
		params.put("fileId", fileId);
		params.put("priority", 0);

		String result = null;
		try {
			/* call 方法正式向指定的接口名发送请求，并把请求参数params传入，返回即是接口的请求结果。 */
			result = module.call("DeleteVodFile", params);
			JSONObject json_result = new JSONObject(result);
			Integer code = (Integer) json_result.get("code");
			rtn = code.equals(QCloudUtil.SUCCESS_CODE);
			if (!rtn) {
				logger.error("cloud video file delete fail,fileId:" + fileId);
				logger.error(json_result.get("mesage"));
			}
		} catch (Exception e) {
			logger.error("video delete error", e);
		}
		return rtn;
	}

	/**
	 * 生成公共参数
	 *
	 * @author ytche
	 * @return
	 * @date 2017年8月21日 下午2:17:33
	 */
	private static TreeMap<String, Object> getConfig() {
		TreeMap<String, Object> config = new TreeMap<String, Object>();
		config.put("SecretId", CommonConstants.TECENT_CLOUD_SECRETID);
		config.put("SecretKey", CommonConstants.TECENT_CLOUD_SECRETKEY);
		/* 请求方法类型 POST、GET */
		config.put("RequestMethod", "GET");
		/* 区域参数，可选: gz:广州; sh:上海; hk:香港; ca:北美;等。 */
		config.put("DefaultRegion", "bj");
		return config;
	}
}
